import 'package:flutter/material.dart';

extension GlobalKeyRect on GlobalKey {
  RenderObject? get renderObject => currentContext?.findRenderObject();

  RenderBox? get renderBox {
    final object = renderObject;
    if (object is RenderBox) {
      return object;
    }
    return null;
  }

  /// 获取 key 对应的 widget 相对于屏幕坐标系的 rect。
  Rect get rect => rectIn();

  /// 获取 key 对应的 widget 相对于某个祖先节点的 rect。
  /// [ancestor] 和 [ancestorKey] 二选一即可。
  Rect rectIn({
    RenderObject? ancestor,
    GlobalKey? ancestorKey,
  }) {
    final box = renderBox;
    if (box == null) {
      return Rect.zero;
    }

    final size = box.size;
    final position = box.localToGlobal(
      Offset.zero,
      ancestor: ancestor ?? ancestorKey?.renderObject,
    );

    return Rect.fromLTWH(
      position.dx,
      position.dy,
      size.width,
      size.height,
    );
  }
}
